#include "stdafx.h"
#include "truetype_loca.h"
#include "truetype.h"

void truetype_loca(truetype_t * tt, tt_table_t * table)
{
	if(!tt || !tt->stream || !table || table->type != tt_table_type_loca)
		return ;
	base_stream_t * stream = tt->stream;

	stream->seeker(stream, table->offset, stream_seek_begin);
	switch(tt->loca_format)
	{
	case tt_loca_format_16:
		{
			tt_loca_16_t * loca = (tt_loca_16_t *)truetype_malloc(sizeof(tt_loca_16_t));
			loca->count = tt->glyf_count + 1;
			loca->length = loca->count << 1;
			loca->data = (uint_16 *)truetype_malloc(loca->length);
			stream->reader(stream, loca->data, loca->length);
#ifdef TT_SMALL_ENDIAN
			for(uint_32 cnt = 0; cnt != loca->count; ++cnt)
				loca->data[cnt] = confirm_big_word(loca->data[cnt]);
#endif // TT_SMALL_ENDIAN
			tt->loca16 = loca;
		}
		break;
	case tt_loca_format_32:
		{
			tt_loca_32_t * loca = (tt_loca_32_t *)truetype_malloc(sizeof(tt_loca_32_t));
			loca->count = tt->glyf_count + 1;
			loca->length = loca->count << 2;
			loca->data = (uint_32 *)truetype_malloc(loca->length);
			stream->reader(stream, loca->data, loca->length);

#ifdef TT_SMALL_ENDIAN
			for(uint_32 cnt = 0; cnt != loca->count; ++cnt)
				loca->data[cnt] = confirm_big_dword(loca->data[cnt]);
#endif // TT_SMALL_ENDIAN
			tt->loca32 = loca;
		}
		break;
	default:
		break;
	}
}

void truetype_loca_index(truetype_t * tt, tt_glyf_index_t * index)
{
	switch(tt->loca_format)
	{
	case tt_loca_format_16:
		truetype_loca_index_16(tt->loca16, index);
		break;
	case tt_loca_format_32:
		truetype_loca_index_32(tt->loca32, index);
		break;
	default:
		break;
	}
}
void truetype_loca_index_16(tt_loca_16_t * loca, tt_glyf_index_t * index)
{
	if(index->loca_index > (int_32)loca->count || index->loca_index < 0)
		return ;

	index->offset = loca->data[index->loca_index];
	index->length = loca->data[index->loca_index + 1] - index->offset;

	if(index->length == 0)
		index->offset = 0;
}

void truetype_loca_index_32(tt_loca_32_t * loca, tt_glyf_index_t * index)
{
	if(index->loca_index > (int_32)loca->count || index->loca_index < 0)
		return ;

	index->offset = loca->data[index->loca_index];
	index->length = loca->data[index->loca_index + 1] - index->offset;

	if(index->length == 0)
		index->offset = 0;
}